package com.hualan.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter( "/*")
public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;

        // 允许所有源访问
        res.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的HTTP方法
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        // 允许的头信息字段
        // 设置响应对象response  可以给前端传递中文数据
        request.setCharacterEncoding("utf-8");

        res.setHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization");
        res.setCharacterEncoding("utf-8");
        res.setContentType("text/html;charset=utf-8");

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 过滤器销毁
    }
}